package com.moco.launcher.alarm;

import java.util.ArrayList;
import java.util.List;

import com.moco.launcher.R;
import com.moco.launcher.activity.AlarmListActivity;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class AlarmListAdapter extends BaseAdapter {

	private Context mContext;
	private List<Alarm> alarms = new ArrayList<Alarm>();
	private AlarmListActivity mActivity;

	public List<Alarm> getAlarms() {
		return alarms;
	}

	public void setAlarms(List<Alarm> alarms) {
		this.alarms = alarms;
	}

	public AlarmListAdapter(Context ctx, AlarmListActivity activity) {
		this.mContext = ctx;
		this.mActivity = activity;
	}

	@Override
	public int getCount() {
		return alarms.size();
	}

	@Override
	public Object getItem(int positon) {
		return alarms.get(positon);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View view, ViewGroup viewgroup) {
		if (null == view) {
			view = LayoutInflater.from(mContext).inflate(
					R.layout.alarm_activity_list_item, null, false);
		}
		TextView alarmTime = (TextView) view.findViewById(R.id.alarm_time);
		ToggleButton toggleButton = (ToggleButton) view
				.findViewById(R.id.alarm_toggle_btn);
		final Alarm alarm = alarms.get(position);
		alarmTime.setText(alarm.getAlarmTimeString());
		toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton cb, boolean isChecked) {
				if (isChecked) {
					// 选中，打开闹铃
					cb.setChecked(isChecked);
				} else {
					// 未选中，关闭闹铃
					cb.setChecked(isChecked);
				}
				alarm.setAlarmActive(isChecked);
				Database.update(alarm);
				mActivity.callMathAlarmScheduleService();
				if (isChecked) {
					Toast.makeText(mContext,
							alarm.getTimeUntilNextAlarmMessage(),
							Toast.LENGTH_LONG).show();
				}
			}
		});
		return view;
	}

}
